import React, { useState, useEffect, useRef, FC } from 'react'
import Taro from '@tarojs/taro'
import { View, Text, Button } from '@tarojs/components'
import { AtInput, AtIcon } from 'taro-ui'
import { JudgingMobile, JudgingPwd } from '@/utils/common'
import api from '@/services/config'
import md5 from 'js-md5/build/md5.min.js'
import './index.scss'

const RetrievePwd: FC = () => {
  const [phone, setPhone] = useState<string>('')
  const [password, setPassword] = useState<string>('')
  const [vercode, setVercode] = useState<string>('')
  const [countDown, setCountDown] = useState<string>('获取验证码')
  const [checked, setchecked] = useState<boolean>(true)
  const intervalRef = useRef<NodeJS.Timeout | undefined>(undefined)

  useEffect(() => {
    return () => {
      clearInterval(Number(intervalRef.current))
    }
  }, [])

  // 表单验证
  function formValidation() {
    const handleStep = [
      {
        judgeKey: !JudgingMobile(phone),
        judgeAdopt: () => {
          Taro.showToast({
            title: '请输入正确的手机号码',
            icon: 'none'
          })
        }
      },
      {
        judgeKey: !JudgingPwd(password),
        judgeAdopt: () => {
          Taro.showToast({
            title: '请输入正确的密码',
            icon: 'none'
          })
        }
      },
      {
        judgeKey: !vercode,
        judgeAdopt: () => {
          Taro.showToast({
            title: '请输入正确的验证码',
            icon: 'none'
          })
        }
      },
      {
        judgeKey: !checked,
        judgeAdopt: () => {
          Taro.showToast({
            title: '请勾选《使用条款和隐私政策》',
            icon: 'none'
          })
        }
      }
    ]
    return handleStep
  }
  // input输入值监控
  function handleChange(value, id) {
    if (id === 1) {
      setPhone(value)
    } else if (id === 2) {
      setPassword(value)
    } else if (id === 3) {
      setVercode(value)
    }
    return value
  }
  //找回密码
  function onSubmit() {
    const formVin = formValidation()
    for (const item of formVin) {
      if (item.judgeKey) {
        item.judgeAdopt()
        return
      }
    }
    api['user/resetPassword']({
      mobile: phone,
      mobileCode: vercode,
      newPassword: md5(password)
    }).then((_) => {
      Taro.showToast({
        title: '找回成功',
        icon: 'none'
      })
      Taro.navigateBack({ delta: 1 })
    })
  }
  // 倒计时
  function countDownFn() {
    let defalutTime = 60
    setCountDown(`${defalutTime--}秒`)
    intervalRef.current = setInterval(() => {
      if (defalutTime >= 0) {
        setCountDown(`${defalutTime--}秒`)
      } else {
        clearInterval(Number(intervalRef.current))
        setCountDown(`获取验证码`)
      }
    }, 1000)
  }
  // 获取验证码
  function getVercode() {
    if (!JudgingMobile(phone)) {
      Taro.showToast({
        title: '请输入正确的手机号后再获取验证码',
        icon: 'none'
      })
      return
    } else if (countDown !== '获取验证码') {
      return
    }
    countDownFn()
    api['user/sendVerifyCode']({
      mobile: phone,
      type: 2
    }).then((_) => {
      Taro.showToast({
        title: '发送成功',
        icon: 'none'
      })
    })
  }

  return (
    <View className='retrievePwd'>
      <View className='retrievePwd-phone'>
        <AtIcon prefixClass='icon' value='sjh' size='25' color='#72b6f5'></AtIcon>
        <AtInput
          className='atinput'
          clear
          name='value1'
          type='phone'
          placeholder='手机号码'
          value={phone}
          onChange={(value) => {
            handleChange(value, 1)
          }}
          border={false}
        />
      </View>
      <View className='retrievePwd-password'>
        <AtIcon prefixClass='icon' value='password' size='25' color='#72b6f5'></AtIcon>
        <AtInput
          className='atinput'
          clear
          name='value2'
          type='password'
          placeholder='请输入6-16位数字、字母的密码'
          value={password}
          onChange={(value) => {
            handleChange(value, 2)
          }}
          border={false}
        />
      </View>
      <View className='retrievePwd-vercode'>
        <AtIcon prefixClass='icon' value='yzm' size='25' color='#72b6f5'></AtIcon>
        <AtInput
          className='atinput'
          name='value3'
          clear
          type='text'
          placeholder='请输入短信验证码'
          value={vercode}
          onChange={(value) => {
            handleChange(value, 3)
          }}
          border={false}
        ></AtInput>
        <View onClick={getVercode} className='retrievePwd-vercode--countdown'>
          {countDown}
        </View>
      </View>
      {/* 使用条款和隐私政策 */}
      <View
        className='retrievePwd-vercode--Policy'
        onClick={(e) => {
          e.stopPropagation()
          console.log(phone)

          setchecked(!checked)
        }}
      >
        {checked ? (
          <AtIcon prefixClass='icon' value='checkbox' size='15' color='#72b6f5'></AtIcon>
        ) : (
          <View className='policy-checkBox'></View>
        )}

        <Text className='policy-msgleft'>我阅读并同意</Text>
        <Text className='policy-msgright'>《使用条款和隐私政策》</Text>
      </View>
      <Button className='retrievePwd-btn' onClick={onSubmit}>
        找回密码
      </Button>
    </View>
  )
}

export default RetrievePwd
